package com.intellipark.androidautonomouscar;

import ioio.lib.util.IOIOLooper;
import ioio.lib.util.IOIOLooperProvider;
import ioio.lib.util.android.IOIOAndroidApplicationHelper;

import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.CameraBridgeViewBase.CvCameraViewFrame;
import org.opencv.android.CameraBridgeViewBase.CvCameraViewListener2;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Range;
import org.opencv.core.Scalar;
import org.opencv.imgproc.Imgproc;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ToggleButton;

// I've copied what was in IOIOActivity to this "normal" activity
public class MainActivity extends Activity implements IOIOLooperProvider, CvCameraViewListener2 		// implements IOIOLooperProvider: from IOIOActivity
{
	protected static final String TAG = null;
	private final IOIOAndroidApplicationHelper helper_ = new IOIOAndroidApplicationHelper(this, this);			// from IOIOActivity
	TextView sensorTextView;
	static TextView colorTextView;
	TextView spotTextView;
	ToggleButton toggleButton;
	EditText setMotorPulseWidth;
	EditText setColorThreshold;
	EditText setIpAddress;
	Button findIpButton;
	Button resetButton;
	Mat mRgba;
	public boolean spot1 = false;
	public boolean trigger = false;
	private CameraBridgeViewBase mOpenCvCameraView;
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
    	
        super.onCreate(savedInstanceState);
         
		
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_main);
    	helper_.create();	
        mOpenCvCameraView = (CameraBridgeViewBase) findViewById(R.id.color_blob_detection_activity_surface_view);
        mOpenCvCameraView.setCvCameraViewListener(this);
        toggleButton = (ToggleButton)findViewById(R.id.ToggleButton);
        sensorTextView = (TextView)findViewById(R.id.sensor2TextView);
        spotTextView = (TextView)findViewById(R.id.spotNumberTextView);
        setMotorPulseWidth = (EditText)findViewById(R.id.editText1);
        setColorThreshold = (EditText)findViewById(R.id.editText2);
        setIpAddress =  (EditText)findViewById(R.id.editText3);
        findIpButton = (Button)findViewById(R.id.button1);
        findIpButton.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
            	String ip = "192.168.1.1";    	
            	ip = setIpAddress.getText().toString();
            	GetSensorValues get =  new GetSensorValues("http://" + ip +":8000/devices/chip_1/analog/0/float", (MainActivity)v.getContext());
             get.execute();
             return false;
            }
           });
       /* resetButton =  (Button)findViewById(R.id.button2);
        resetButton.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
            
             return false;
            }
           });*/
        enableUi(false);
        
    }
    
    private BaseLoaderCallback  mLoaderCallback = new BaseLoaderCallback(this) {
        @Override
        public void onManagerConnected(int status) {
            switch (status) {
                case LoaderCallbackInterface.SUCCESS:
                {
                    Log.i(TAG, "OpenCV loaded successfully");
                    mOpenCvCameraView.enableView();
                
                } break;
                default:
                {
                    super.onManagerConnected(status);
                } break;
            }
        }
    };
    
	public void enableUi(final boolean enable) 
	{
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				trigger = true;
				toggleButton.setEnabled(enable);
			}
		});
	}
	
	public void setText(final String sensorReading) 
	{
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				sensorTextView.setText(sensorReading);
				
			}
		});
	}
	
	/****************************************************** functions from IOIOActivity *********************************************************************************/
	
	protected IOIOLooper createIOIOLooper() 
	{
		return new IOIO_thread(this);				//  !!!!!!!!!!!!!!!!!   create our own IOIO thread (Looper) with a reference to this activity
	}
	
	@Override
	public IOIOLooper createIOIOLooper(String connectionType, Object extra) 
	{
		return createIOIOLooper();
	}
    @Override
    public void onPause()
    {
        super.onPause();
        if (mOpenCvCameraView != null)
            mOpenCvCameraView.disableView();
    }

    @Override
    public void onResume()
    {
        super.onResume();
        OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_8, this, mLoaderCallback);
    }
	
	@Override
	protected void onDestroy() 
	{
		helper_.destroy();
		super.onDestroy();
		  if (mOpenCvCameraView != null)
	            mOpenCvCameraView.disableView();
	}

	@Override
	protected void onStart() 
	{
		super.onStart();
		helper_.start();
	}

	@Override
	protected void onStop() 
	{
		helper_.stop();
		super.onStop();
	}

	@Override
	protected void onNewIntent(Intent intent) 
	{
		super.onNewIntent(intent);
		if ((intent.getFlags() & Intent.FLAG_ACTIVITY_NEW_TASK) != 0) 
		{
			helper_.restart();
		}
	
	}

    public void onCameraViewStarted(int width, int height) {
        mRgba = new Mat(height, width, CvType.CV_8UC3);
    }

    public void onCameraViewStopped() {
        mRgba.release();
    }
public static int whiteValue = 100000;

    public Mat onCameraFrame(final CvCameraViewFrame inputFrame) {
    /*	
    	try {
			Thread.sleep(100);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
                	 mRgba = inputFrame.rgba();
                	 if(trigger == true){
                     Mat mHsv = new Mat();
                     int height = mRgba.height();
                     int width = mRgba.width();
                     Mat mSub = new Mat();
                     Mat mTemp1 = new Mat();
                     Imgproc.cvtColor(mRgba,mHsv,Imgproc.COLOR_RGB2HSV);
                     mSub = mHsv.submat( new Range(height/4, height/2),Range.all());
                     //Check for red
                     if(spot1){
                    Core.inRange(mSub, new Scalar(0, 100, 30), new Scalar(5, 255, 255), mTemp1);
                     }
                     else{
                    	 Core.inRange(mSub, new Scalar(110, 100, 30), new Scalar(115, 255, 255), mTemp1);                     }
                    Mat m = new Mat();
                     Core.extractChannel(mTemp1, m, 0);
                      whiteValue = Core.countNonZero(m);
                     System.out.println("Value of n: " +  whiteValue);
                    // MainActivity.colorTextView_.setText(""+whiteValue);
                     m.release();
          	        mHsv.release();
          	        mTemp1.release();
          	        mSub.release();
                	 }
                	 
         	        mRgba.release();
        //return mTemp1;
        return inputFrame.rgba();
    }
	}
	